//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.siecom.tools;

import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Locale;
import java.util.concurrent.ArrayBlockingQueue;

public class LogUtil {
    private static final String TAG = LogUtil.class.getSimpleName();
    private static final boolean DEBUG = true;
    private static final boolean LOG_TO_FILE_IN_DEBUG_MODE = false;
    private static LogUtil.SaveSDKLog saveSDKLog;
    private static ArrayBlockingQueue<String[]> logQueue;
    public static String sdkClient = "Common";

    public LogUtil() {
    }

    public static void e(String tag, Object msg) {
        log(tag, msg, 'e');
    }

    public static void i(String tag, Object msg) {
        log(tag, msg, 'i');
    }

    private static void log(String tag, Object msg, char logLevel) {
        if(tag == null) {
            tag = "null";
        }

        if(msg == null) {
            msg = "null";
        }

        String str;
        if(msg instanceof Bundle) {
            Bundle bundle = (Bundle)msg;
            StringBuilder builder = new StringBuilder();

            for(Iterator var7 = bundle.keySet().iterator(); var7.hasNext(); builder.append("\n")) {
                String key = (String)var7.next();
                builder.append('"');
                builder.append(key);
                builder.append('"');
                builder.append("    :    ");
                Object value = bundle.get(key);
                if(value == null) {
                    builder.append("null");
                } else if(!(value instanceof String)) {
                    builder.append(value.toString());
                } else {
                    builder.append('"');
                    builder.append(value.toString());
                    builder.append('"');
                }
            }

            str = builder.toString();
        } else {
            str = msg.toString();
        }

        switch(logLevel) {
            case 'e':
                Log.e(tag, str);
            case 'f':
            case 'g':
            case 'h':
            default:
                break;
            case 'i':
                Log.i(tag, str);
        }

    }

    public static void logE2KOnce(String tag, String message) {
        int offset;
        for(offset = 0; message.length() - offset > 2048; offset += 2048) {
            Log.e(tag, message.substring(offset, offset + 2048));
        }

        e(tag, message.substring(offset, message.length()));
    }

    public static void logI2KOnce(String tag, String message) {
        int offset;
        for(offset = 0; message.length() - offset > 2048; offset += 2048) {
            Log.i(tag, message.substring(offset, offset + 2048));
        }

        i(tag, message.substring(offset, message.length()));
    }

    public static void logWithInfo(String msg, String level, StackTraceElement[] elements) {
        int lineNum = elements[2].getLineNumber();
        String fileName = elements[2].getFileName();
        String methodName = elements[2].getMethodName();
        if(level.equals("e")) {
            Log.e(fileName, methodName + "[" + lineNum + "]:" + msg);
        } else if(level.equals("w")) {
            Log.w(fileName, methodName + "[" + lineNum + "]:" + msg);
        } else if(level.equals("i")) {
            Log.i(fileName, methodName + "[" + lineNum + "]:" + msg);
        } else if(level.equals("d")) {
            Log.d(fileName, methodName + "[" + lineNum + "]:" + msg);
        } else if(level.equals("v")) {
            Log.v(fileName, methodName + "[" + lineNum + "]:" + msg);
        }

    }

    public static class SaveLog extends Thread {
        private File saveFile;

        public SaveLog() {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HHmmss", Locale.getDefault());
            String dateStr = dateFormat.format(new Date());
            String savePath = Environment.getExternalStorageDirectory() + "/01SunyardDebug/sdkLogFor" + LogUtil.sdkClient + "-" + dateStr + ".txt";
            this.init(new File(savePath));
        }

        public SaveLog(String savePath) {
            this.init(new File(savePath));
        }

        public SaveLog(File saveFile) {
            this.init(saveFile);
        }

        private void init(File saveFile) {
            File parentFile = saveFile.getParentFile();
            if(!parentFile.exists()) {
                parentFile.mkdirs();
            }

            this.saveFile = saveFile;
            this.start();
        }

        public void run() {
            while(true) {
                Log.i(LogUtil.TAG, "开始保存Log");
                FileOutputStream fos = null;
                Process process = null;
                BufferedReader mReader = null;

                try {
                    fos = new FileOutputStream(this.saveFile, true);
                    int pId = android.os.Process.myPid();
                    String pIdStr = String.valueOf(pId);
                    String cmds = "logcat *:v -v threadtime -v time | grep \"(" + pId + ")\"";
                    process = Runtime.getRuntime().exec(cmds);
                    mReader = new BufferedReader(new InputStreamReader(process.getInputStream()), 1024);
                    String line = mReader.readLine();

                    while((line = mReader.readLine()) != null) {
                        if(line.length() != 0 && fos != null && line.contains(pIdStr)) {
                            fos.write((line + "\r\n").getBytes());
                        }
                    }

                    return;
                } catch (Exception var20) {
                    Log.i(LogUtil.TAG, "保存Log时出现异常");
                    var20.printStackTrace();
                } finally {
                    if(process != null) {
                        process.destroy();
                    }

                    if(mReader != null) {
                        try {
                            mReader.close();
                        } catch (IOException var19) {
                            var19.printStackTrace();
                        }
                    }

                    if(fos != null) {
                        try {
                            fos.close();
                        } catch (IOException var18) {
                            var18.printStackTrace();
                        }
                    }

                }

                Log.i(LogUtil.TAG, "结束保存Log");
            }
        }
    }

    public static class SaveSDKLog extends Thread {
        private File saveFile;

        public SaveSDKLog() {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HHmmss", Locale.getDefault());
            String dateStr = dateFormat.format(new Date());
            String savePath = Environment.getExternalStorageDirectory() + "/01SunyardDebug/sdkLog-" + dateStr + ".txt";
            this.init(new File(savePath));
        }

        public SaveSDKLog(String savePath) {
            this.init(new File(savePath));
        }

        public SaveSDKLog(File saveFile) {
            this.init(saveFile);
        }

        private void init(File saveFile) {
            File parentFile = saveFile.getParentFile();
            if(!parentFile.exists()) {
                parentFile.mkdirs();
            }

            this.saveFile = saveFile;
            this.start();
        }

        public void run() {
            while(true) {
                FileOutputStream output = null;

                try {
                    output = new FileOutputStream(this.saveFile);
                    DateFormat dateFormat = new SimpleDateFormat("yyMMdd HH:mm:ss:SSS", Locale.getDefault());
                    int count = 0;

                    while(true) {
                        ++count;
                        if(count % 10 == 0 && !this.saveFile.exists()) {
                            throw new RuntimeException("log文件被删除, 重新创建");
                        }

                        String[] tagAndMsg = (String[])LogUtil.logQueue.take();
                        String tag = tagAndMsg[0];
                        String msg = tagAndMsg[1];
                        String dateStr = dateFormat.format(new Date());
                        StringBuilder builder = new StringBuilder(dateStr);
                        builder.append(' ');
                        builder.append(tag);
                        builder.append('\n');
                        builder.append("                        ");
                        builder.append(msg);
                        builder.append('\n');
                        output.write(builder.toString().getBytes());
                    }
                } catch (Exception var16) {
                    var16.printStackTrace();
                } finally {
                    if(output != null) {
                        try {
                            output.close();
                        } catch (IOException var15) {
                            var15.printStackTrace();
                        }
                    }

                }
            }
        }

        public void log(String tag, String msg) {
            LogUtil.logQueue.add(new String[]{tag, msg});
        }
    }


    public static LogRunable logRunable;
    public static SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
    public static SimpleDateFormat formatSFM = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
    public static final String LOG_DIR = "/sdcard/";

    public static void save(String infoStr,String module){

        logRunable = new LogRunable(infoStr,module);
        SingletonThreadPool.getInstance().execute(logRunable);
    }
    public static synchronized String saveInfo2File(String infoStr,String module) {
        StringBuffer sb = new StringBuffer();
        sb.append("\n");
        sb.append(formatSFM.format(new Date()));
        sb.append("  ");
        sb.append(infoStr);

        String time = format.format(new Date());
        String fileName = time   + ".txt";
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            try {
                File dir = new File(LOG_DIR + module);

//                File dir = new File("D:\\A218Log\\" + module);
                LogUtil.i(TAG, dir.toString());
                if (!dir.exists())
                    dir.mkdirs();
                FileOutputStream fos = new FileOutputStream(new File(dir,
                        fileName),true);
                long size = getFolderSize(dir);
                System.out.println("size=" + size);

                File file = new File(dir.getAbsolutePath());
                if(file.isDirectory()){
                    File[] files = file.listFiles();
                    for(int i = 0;i < (files.length - 5);i++){
                        System.out.println("删除文件："+files[i].getName());
                        files[i].delete();
                    }
                }
//                if (size > 104857600) {
//                    CrashHandler.deleteFolderFile(dir.getAbsolutePath(),false);
//                }
                fos.write(sb.toString().getBytes());
                fos.close();
                return sb.toString();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    /**
     * 获取文件夹大小
     * @param file File实例
     * @return long
     */
    public static long getFolderSize(java.io.File file){

        long size = 0;
        try {
            java.io.File[] fileList = file.listFiles();
            for (int i = 0; i < fileList.length; i++)
            {
                if (fileList[i].isDirectory())
                {
                    size = size + getFolderSize(fileList[i]);

                }else{
                    size = size + fileList[i].length();

                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //return size/1048576;
        return size;
    }
    public static class LogRunable implements Runnable {

        public String logStr;
        public String module;
        public LogRunable(String str,String module){
            this.logStr = str;
            this.module = module;
        }
        @Override
        public void run() {
            saveInfo2File(logStr,module);
        }
    }
}
